/**
 * 
 */
package org.posta.data;

import java.util.List;

import org.posta.data.user.User;

import com.db4o.Db4o;
import com.db4o.ObjectContainer;
import com.db4o.constraints.UniqueFieldValueConstraint;
import com.db4o.query.Predicate;
import com.google.inject.Inject;

/**
 * @author mmerli
 */
public class UserStore
{
    private DataStore dataStore;
    
    static
    {
        Db4o.configure().add(new UniqueFieldValueConstraint(User.class, "userName"));
    }
    
    @Inject
    public UserStore(DataStore dataStore)
    {
        this.dataStore = dataStore;
    }
    
    /*
     * (non-Javadoc)
     * 
     * @see org.posta.data.UserStore#getByName(java.lang.String)
     */
    public User getByName(final String userName)
    {
        ObjectContainer db = dataStore.getDb();
        
        List<User> users = db.query(new Predicate<User>() {
            public boolean match(User user)
            {
                return user.getUserName().equals(userName);
            }
        });
        
        if (users.size() > 0)
            return users.get(0);
        
        // Create a new user
        User user = new User(userName, "xxx");
        store(user);
        return user;
    }
    
    /*
     * (non-Javadoc)
     * 
     * @see org.posta.data.UserStore#store(org.posta.data.user.User)
     */
    public void store(User user)
    {
        dataStore.getDb().set(user);
        dataStore.getDb().commit();
    }
    
}
